package com.itheima.aop;

import com.alibaba.fastjson.JSONObject;
import com.itheima.mapper.OperateLogMapper;
import com.itheima.pojo.OperateLog;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    //直接注入一个对象，可以拿到当前请求的请求对象
    @Autowired
    private HttpServletRequest httpServletRequest;

    @Around("@annotation(com.itheima.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
        //操作人id 当前登陆员工id
        //获取请求头中的令牌并且解析令牌
        String jwt = httpServletRequest.getHeader("token");
        Claims claims = JwtUtils.parseJWT(jwt);
        Integer operateUser = (Integer) claims.get("id");
        //操作时间
        LocalDateTime operateTime = LocalDateTime.now();
        //操作类类名
        String className = joinPoint.getTarget().getClass().getName();
        //操作方法参数
        Object[] getargs = joinPoint.getArgs();
        String methodParams = Arrays.toString(getargs);
        //操作方法名
        String methodName = joinPoint.getSignature().getName();

        long begin = System.currentTimeMillis();
        //方法返回值
        //调用原始目标方法运行
        Object result = joinPoint.proceed();
        long end = System.currentTimeMillis();
        String returnValue = JSONObject.toJSONString(result);

        //操作耗时
        Long costTime = end-begin;
        //记录操作日志
        OperateLog operatelog = new OperateLog(null,operateUser,operateTime,className,
                methodName,methodParams,returnValue,costTime);

        operateLogMapper.insert(operatelog);

        log.info("AOP记录操作日志：{}",operatelog);
        return result;


    }
}
